﻿/*-------------------------------------------------------------------------
* 命名空间: ScreenCapture.ValueConverters/NotNullConverter
* 类       名: NotNullConverter
* 功      能:  TD
* 时      间:  2023/12/5 9:03:39
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using System;
using System.Collections;
using System.Globalization;
using System.Windows;

namespace ScreenCapture.ValueConverters
{
    /// <summary>
    /// 非空转换器(如果非空,返回true,否则返回false.
    /// </summary>
    public class NotNullConverter : OneWayConverter
    {
        public override object Convert(object Value, Type TargetType, object Parameter, CultureInfo Culture)
        {
            // 先根据Value是否是null获取默认值.
            bool res = Value != null;
            switch (Value)
            {
                case ICollection collection:
                    res = collection.Count != 0;
                    break;
                case string str:
                    res = !string.IsNullOrWhiteSpace(str);
                    break;
                case int i:
                    res = i != 0;
                    break;
                case double d:
                    res = Math.Abs(d) > 0.001;
                    break;
            }
            // 看看是否需要反转结果,根据parameter.
            if ((Parameter is bool inverse || Parameter is string s && bool.TryParse(s, out inverse)) && inverse)
                res = !res;

            // 如果目标类型是是否显示,然后要返回其是否控件的是否显示的属性
            if (TargetType == typeof(Visibility))
                return res ? Visibility.Visible : Visibility.Collapsed;
            return res;
        }
    }
}
